package com.zb.uniman.service.impl;

import com.zb.uniman.common.ResultMap;
import com.zb.uniman.model.LoginUser;
import com.zb.uniman.model.SysUser;
import com.zb.uniman.service.LoginService;
import com.zb.uniman.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Author:B
 * Description:
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    /*
    登录流程：
    user{id:"",username:"",password:""}
    根据username,password查询用户，创建jwt返回前端
    认证通过token查到user对象，放行
     */
    @Override
    public ResultMap login(SysUser user) {
        UsernamePasswordAuthenticationToken passwordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(passwordAuthenticationToken);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败，authenticate为空");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);

        System.out.println("这是token----------------------" + jwt);
//        todo存到redis  --->map
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResultMap(200, "success", map);
    }
}
